import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'dart:developer' as developer;
import '../config/app_config.dart';
import '../models/api_response.dart';
import '../errors/error_handler.dart';
import '../errors/app_exception.dart';
import '../constants/api_endpoints.dart';
import 'error_logger_service.dart';
import '../../shared/storage/storage_service.dart';

class ApiService {
  late final Dio _dio;
  final StorageService _storageService;

  ApiService(this._storageService) {
    // 验证 URL 格式
    final apiUrl = AppConfig.apiBaseUrl;
    try {
      Uri.parse(apiUrl);
    } catch (e) {
      developer.log('❌ Invalid URL format: $apiUrl, Error: $e', name: 'ApiService', level: 1000);
      throw Exception('Invalid API URL format: $apiUrl');
    }
    
    _dio = Dio(
      BaseOptions(
        baseUrl: apiUrl,
        connectTimeout: AppConfig.connectTimeout,
        receiveTimeout: AppConfig.receiveTimeout,
        headers: {
          'Content-Type': 'application/json',
        },
        // 添加更多配置以确保连接正常
        followRedirects: true,
        validateStatus: (status) {
          return status != null && status < 500;
        },
      ),
    );

    // 添加请求拦截器：全局自动添加 token 到所有请求
    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) async {
          // 检查是否是登录接口（不需要 token）
          final isLoginEndpoint = ApiEndpoints.isLoginEndpoint(options.path);
          
          // 如果不是登录接口，自动添加 token
          if (!isLoginEndpoint) {
            final token = await _storageService.getToken();
            if (token != null && token.isNotEmpty) {
              // 全局自动添加 Authorization header
              options.headers['Authorization'] = 'Bearer $token';
              // 调试日志：确认 token 已添加
              developer.log(
                '✅ Token added to request: ${options.method} ${options.path}',
                name: 'ApiService',
                level: 900,
              );
            } else {
              // 如果没有 token，记录警告
              developer.log(
                '⚠️ Request without token: ${options.method} ${options.path}',
                name: 'ApiService',
                level: 1000,
              );
            }
          }
          
          return handler.next(options);
        },
        onResponse: (response, handler) {
          return handler.next(response);
        },
        onError: (error, handler) {
          // 统一错误处理
          if (error.response?.statusCode == 401) {
            // Token 过期或无效，记录详细信息
            final requestOptions = error.requestOptions;
            final authHeader = requestOptions.headers['Authorization'];
            developer.log(
              '❌ 401 Unauthorized: ${requestOptions.method} ${requestOptions.uri}',
              name: 'ApiService',
              level: 1000,
            );
            developer.log(
              '   Authorization header: ${authHeader != null ? "Present (${authHeader.toString().substring(0, authHeader.toString().length > 20 ? 20 : authHeader.toString().length)}...)" : "Missing"}',
              name: 'ApiService',
              level: 1000,
            );
            // Token 过期，清除本地存储
            _storageService.clearToken();
          }
          
          // 错误日志（仅记录错误，不记录正常请求）
          if (error is DioException) {
            developer.log(
              'DioException: ${error.type} - ${error.message} - ${error.requestOptions.uri}',
              name: 'ApiService',
              level: 1000,
            );
          }
          
          // 记录错误日志
          ErrorLoggerService.logError(
            error,
            context: 'API Request',
            extra: {
              'path': error.requestOptions.path,
              'method': error.requestOptions.method,
              'baseUrl': error.requestOptions.baseUrl,
              'fullUrl': error.requestOptions.uri.toString(),
            },
          );
          
          return handler.next(error);
        },
      ),
    );
  }

  Future<ApiResponse<T>> get<T>(
    String path, {
    Map<String, dynamic>? queryParameters,
    T? Function(dynamic)? fromJson,
  }) async {
    try {
      final response = await _dio.get(
        path,
        queryParameters: queryParameters,
      );
      return _handleResponse<T>(response, fromJson);
    } catch (e) {
      return _handleError<T>(e);
    }
  }

  Future<ApiResponse<T>> post<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    T? Function(dynamic)? fromJson,
  }) async {
    try {
      final response = await _dio.post(
        path,
        data: data,
        queryParameters: queryParameters,
      );
      return _handleResponse<T>(response, fromJson);
    } catch (e) {
      return _handleError<T>(e);
    }
  }

  Future<ApiResponse<T>> put<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    T? Function(dynamic)? fromJson,
  }) async {
    try {
      final response = await _dio.put(
        path,
        data: data,
        queryParameters: queryParameters,
      );
      return _handleResponse<T>(response, fromJson);
    } catch (e) {
      return _handleError<T>(e);
    }
  }

  Future<ApiResponse<T>> delete<T>(
    String path, {
    Map<String, dynamic>? queryParameters,
    T? Function(dynamic)? fromJson,
  }) async {
    try {
      final response = await _dio.delete(
        path,
        queryParameters: queryParameters,
      );
      return _handleResponse<T>(response, fromJson);
    } catch (e) {
      return _handleError<T>(e);
    }
  }

  ApiResponse<T> _handleResponse<T>(
    Response response,
    T? Function(dynamic)? fromJson,
  ) {
    try {
      final data = response.data;
      final statusCode = response.statusCode ?? 200;
      
      // 记录响应信息（用于调试）
      developer.log(
        '📥 API Response: status=$statusCode, path=${response.requestOptions.path}',
        name: 'ApiService',
        level: 900,
      );
      
      if (data is Map<String, dynamic>) {
        // 检查是否是标准 ApiResponse 格式（有 code 和 message 字段）
        if (data.containsKey('code') || (data.containsKey('message') && !data.containsKey('status'))) {
          // 标准格式，使用 fromJson 解析
          final apiResponse = ApiResponse.fromJson(data, fromJson);
          
          // 记录解析结果
          developer.log(
            '📦 Parsed ApiResponse: code=${apiResponse.code}, success=${apiResponse.success}, message=${apiResponse.message}',
            name: 'ApiService',
            level: 900,
          );
          
          return apiResponse;
        } else if (data.containsKey('status') && data['status'] == 'ok') {
          // 后端返回 {status: "ok"} 格式，表示成功
          // 尝试从 data 字段中解析，如果没有 data 字段，则使用整个响应
          T? parsedData;
          if (data.containsKey('data') && fromJson != null) {
            try {
              parsedData = fromJson(data['data']);
            } catch (e) {
              developer.log(
                '⚠️ Failed to parse data field: $e',
                name: 'ApiService',
                level: 1000,
              );
            }
          } else if (fromJson != null) {
            // 尝试解析整个响应
            try {
              parsedData = fromJson(data);
            } catch (e) {
              developer.log(
                '⚠️ Failed to parse response as data: $e, response: $data',
                name: 'ApiService',
                level: 1000,
              );
            }
          }
          
          return ApiResponse<T>(
            code: statusCode,
            message: 'Success',
            data: parsedData,
            success: true,
          );
        } else {
          // 非标准格式（直接返回数据，如 {user: {...}, token: ...}）
          // 将整个响应作为 data 处理
          T? parsedData;
          if (fromJson != null) {
            try {
              parsedData = fromJson(data);
            } catch (e) {
              developer.log(
                '⚠️ Failed to parse data with fromJson: $e, data: $data',
                name: 'ApiService',
                level: 1000,
              );
              // 如果解析失败，尝试直接转换
              parsedData = data as T?;
            }
          } else {
            parsedData = data as T?;
          }
          
          return ApiResponse<T>(
            code: statusCode,
            message: statusCode == 200 ? 'Success' : 'Request completed',
            data: parsedData,
            success: statusCode >= 200 && statusCode < 300,
          );
        }
      } else {
        // 非 Map 类型，直接作为 data
        T? parsedData;
        if (fromJson != null) {
          try {
            parsedData = fromJson(data);
          } catch (e) {
            developer.log(
              '⚠️ Failed to parse non-map data with fromJson: $e, data: $data',
              name: 'ApiService',
              level: 1000,
            );
            parsedData = data as T?;
          }
        } else {
          parsedData = data as T?;
        }
        
        return ApiResponse<T>(
          code: statusCode,
          message: statusCode == 200 ? 'Success' : 'Request completed',
          data: parsedData,
          success: statusCode >= 200 && statusCode < 300,
        );
      }
    } catch (e, stackTrace) {
      developer.log(
        '❌ Parse error: $e\nStack trace: $stackTrace',
        name: 'ApiService',
        level: 1000,
      );
      return ApiResponse<T>(
        code: 500,
        message: '响应解析失败: $e',
        success: false,
      );
    }
  }

  ApiResponse<T> _handleError<T>(dynamic error) {
    AppException appException;
    
    if (error is DioException) {
      appException = ErrorHandler.handleDioError(error);
    } else if (error is AppException) {
      appException = error;
    } else {
      appException = AppException(error.toString());
    }
    
    return ApiResponse<T>(
      code: appException.code ?? 500,
      message: appException.message,
      success: false,
    );
  }
}

